
import { addUserDao, findUserDao, updateUserDao } from '../Dao/userDao.js'
import { getRandomStr } from '../tools/index.js'
import md5 from 'md5'
import fs from 'fs/promises'
import jwt from 'jsonwebtoken'
import path from 'path'

export const registerServ = async ({username,nickname})=>{
    if(!nickname){
        nickname = '新用户' + getRandomStr(6)
    }
    const dirs = await fs.readdir(path.resolve(import.meta.dirname, '../static/avatar'))

    const avatar = dirs[Math.floor(Math.random() * dirs.length)]
    return await addUserDao({
        username,
        nickname,
        avatar: 'http://localhost:8090/'+avatar,
        password: md5("123123")
    }) 
}
export const loginServ = async (userInfo)=>{
    // 查数据对比
    const user = await findUserDao(userInfo.username)

    if(!user){
        return {
            code:1,
            msg:'用户名不存在'
        }
    }

    if(md5(userInfo.password)===user.password){
        // 登录成功
        // 是否要免密登录30天
        console.log(userInfo.noLogin);
        if(userInfo.noLogin){
            // 免密登录
            // jwt
            // 1.签名 ===> 令牌
            // 2.后续访问 ====> 解析令牌
            const token = jwt.sign({data:user.username},'buka',{
                expiresIn: "30d"
            });
            // // 解析签名
            // const values = jwt.verify(token, 'buka')
            // console.log(values);
            return{
                code:0,
                msg:"登陆成功",
                token,
                data:user,
            }
        }else{
            // 没有勾选免密登录 返回用户信息就可以
            const token = jwt.sign({data:user.username},'buka',{
                expiresIn: "1d"
            })
            return{
                code:0,
                msg:"登录成功",
                data:user,
                token,
            }
        }
    }else{
        return{
            code :1,
            msg:"密码错误"
        }
    }
}
export const checkAuthServ = async(username,password)=>{
    const user = await findUserDao(username)
    if(user){
        if(user.password === md5(password)){
            return{
                code:0,
                msg:'ok'
            }
        }else{
            return{
                code:1,
                msg:'密码错误'
            }
        }
    }else{
        return {
            code:1,
            msg:'用户不存在'
        }
    }
}

export const updatePwdServ = async (username,password) => {
    // 完成数据库的一个更新操作
    return await updateUserDao(username,{password: md5(password)})
}

export const updateUserServ = async (username,updateObj) => {
    const res = await updateUserDao(username,updateObj)
    return {
        code: 0,
        msg: 'ok',
        data: res
    }
}